﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SAM.Framework.Repository.Entities
{
    public abstract class Entity : Entity<int>, IEntity
    {

    }

    [Serializable]
    public abstract class Entity<TPrimaryKey> : IEntity<TPrimaryKey>
    {
        public virtual TPrimaryKey Id { get; set; }

        /// <summary>
        /// 判断实体是否未持久化
        /// </summary>
        /// <returns>如果对象未持久化则返回true，否则返回false</returns>
        public virtual bool IsTransient()
        {
            //判断思路，取对象的Id字段的值 和c#默认构造器的默认值进行比较
            //如果相等，则认为对象未持久化，举例：对象的主键是int 类型的Id，如果Id<=0，则认为对象未持久化，应该执行Insert操作
            //如果Id>0 则认为对象已经持久化了，应该执行Update操作
            if (EqualityComparer<TPrimaryKey>.Default.Equals(Id, default(TPrimaryKey)))
            {
                return true;
            }

            //Workaround for EF Core since it sets int/long to min value when attaching to dbcontext
            if (typeof(TPrimaryKey) == typeof(int))
            {
                return Convert.ToInt32(Id) <= 0;
            }

            if (typeof(TPrimaryKey) == typeof(long))
            {
                return Convert.ToInt64(Id) <= 0;
            }

            return false;
        }
        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }
}
